package znet

import (
	"errors"
	"fmt"
	"sync"
	"zinx-tianjing-study/ziface"
)

type ConnectionManager struct {
	coons    map[uint32]ziface.IConnection
	coonlock sync.RWMutex
}

// NewConnectionManager 初始化一个新的连接管理器实例，并打印初始化日志
func NewConnectionManager() *ConnectionManager {
	manager := &ConnectionManager{
		coons: make(map[uint32]ziface.IConnection),
	}
	fmt.Println("Connection Manager created.")
	return manager
}

// Add 添加一个连接到管理器中，并打印添加日志
func (cm *ConnectionManager) Add(coon ziface.IConnection) {
	cm.coonlock.Lock()
	defer cm.coonlock.Unlock()

	cm.coons[coon.GetConnectionID()] = coon
	fmt.Printf("Connection added, ID: %d\n", coon.GetConnectionID())
}

// Remove 从管理器中移除一个连接，并打印移除日志
func (cm *ConnectionManager) Remove(coon ziface.IConnection) {
	cm.coonlock.Lock()
	defer cm.coonlock.Unlock()

	delete(cm.coons, coon.GetConnectionID())
	fmt.Printf("Connection removed, ID: %d\n", coon.GetConnectionID())
}

// Get 根据 ConnID 获取一个连接，并打印相关日志
func (cm *ConnectionManager) Get(connID uint32) (ziface.IConnection, error) {
	cm.coonlock.RLock()
	defer cm.coonlock.RUnlock()

	conn, ok := cm.coons[connID]
	if !ok {
		fmt.Printf("Failed to find connection by ID: %d\n", connID)
		return nil, errors.New("connection not found")
	}
	fmt.Printf("Found connection by ID: %d\n", connID)
	return conn, nil
}

// Len 返回当前连接数，并打印当前连接数量
func (cm *ConnectionManager) Len() uint32 {
	cm.coonlock.RLock()
	defer cm.coonlock.RUnlock()

	count := uint32(len(cm.coons))
	fmt.Printf("Current connections count: %d\n", count)
	return count
}

// ClearConn 清空所有连接，并打印每个被清除的连接的信息
func (cm *ConnectionManager) ClearConn() {
	cm.coonlock.Lock()
	defer cm.coonlock.Unlock()

	for id := range cm.coons {
		conn := cm.coons[id]
		conn.Stop() // 假设 Stop 方法存在用于关闭连接
		delete(cm.coons, id)
		fmt.Printf("Connection cleared and stopped, ID: %d\n", id)
	}
}
